package com.example.parking.service;

import com.example.parking.entity.ParkingSpace;
import com.example.parking.entity.Vehicle;
import com.example.parking.repository.ParkingSpaceRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ParkingSpaceService {
    @Autowired
    private ParkingSpaceRepository parkingSpaceRepository;

    // 查询所有车位
    public List<ParkingSpace> getAllParkingSpaces() {
        return parkingSpaceRepository.findAll();
    }

    // 条件查询车位
    public List<ParkingSpace> searchParkingSpaces(String spaceNumber, String area) {
        if (spaceNumber != null && !spaceNumber.isEmpty()) {
            return parkingSpaceRepository.findBySpaceNumberContaining(spaceNumber);
        } else if (area != null && !area.isEmpty()) {
            return parkingSpaceRepository.findByArea(area);
        }
        return parkingSpaceRepository.findAll();
    }

    // 统计空闲车位数量
    public int countAvailableSpaces() {
        return parkingSpaceRepository.countByStatus("空闲");
    }

    // 分配车位
    public ParkingSpace assignParkingSpace(Long spaceId, Vehicle vehicle) {
        ParkingSpace space = parkingSpaceRepository.findById(spaceId).orElse(null);
        if (space != null && "空闲".equals(space.getStatus())) {
            space.setStatus("已占用");
            space.setVehicle(vehicle);
            return parkingSpaceRepository.save(space);
        }
        return null;
    }

    // 回收车位
    public ParkingSpace releaseParkingSpace(Long spaceId) {
        ParkingSpace space = parkingSpaceRepository.findById(spaceId).orElse(null);
        if (space != null && "已占用".equals(space.getStatus())) {
            space.setStatus("空闲");
            space.setVehicle(null);
            return parkingSpaceRepository.save(space);
        }
        return null;
    }
}